package com.thwj.common.utils.sms;

import cn.hutool.json.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.thwj.common.exception.CustomException;
import com.thwj.framework.config.SmsConfig;
import com.thwj.framework.web.domain.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * <b>功能名：</b>SmsAliUtils<br>
 * <b>说明：</b><br>
 * <b>著作权：</b> Copyright (C) 2019   CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2020-06-08 hufeng
 */
@Component
public class SmsUtils {
    @Autowired
    private SmsConfig smsAlliyunConfig;

    private static SmsConfig smsAlliyunConfigs;

    private static final Logger log = LoggerFactory.getLogger(SmsUtils.class);

    /**
     * 初始化获取配置
     */
    @PostConstruct
    public void init() {
        smsAlliyunConfigs = this.smsAlliyunConfig;
    }

    /**
     * 调用阿里短信服务
     *
     * @param phone 手机号
     * @param map   内容 json
     * @return
     */
    public static boolean sendSmsByAli(String phone, Map<String, String> map, String template) throws ClientException {
        JSONObject jsonArray = new JSONObject();
        for (String maps : map.keySet()) {
            jsonArray.putOnce(maps, map.get(maps));
        }
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        //短信API产品名称（短信产品名固定，无需修改）
        final String product = smsAlliyunConfigs.getProduct();
        //短信API产品域名（接口地址固定，无需修改）
        final String domain = smsAlliyunConfigs.getDomain();
        IClientProfile profile = DefaultProfile.getProfile(smsAlliyunConfigs.getName(), smsAlliyunConfigs.getId(), smsAlliyunConfigs.getSecret());
        DefaultProfile.addEndpoint(smsAlliyunConfigs.getName(), smsAlliyunConfigs.getName(), product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(phone);
        request.setSignName(smsAlliyunConfigs.getSignCode());
        request.setTemplateCode(template);
        request.setTemplateParam(jsonArray.toString());
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            return true;
        } else {
            if ("isv.BUSINESS_LIMIT_CONTROL".equals(sendSmsResponse.getCode())) {
                log.error("短信通知：" + sendSmsResponse.getMessage());
                throw new CustomException(ResultCode.BUSINESS_LIMIT_CONTROL);
            } else {
                log.error("短信发送失败码：" + sendSmsResponse.getCode());
                log.error("短信发送失败信息：" + sendSmsResponse.getMessage());
                throw new CustomException(ResultCode.SMS_FAILURE);
            }
        }
    }

}
